package com.example.smartg;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Response;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.smartg.ui.weixin.WeixinScanFragment;
import com.example.smartg.utils.LogoutDialogUtil;
import com.example.smartg.utils.TextSpeech;
import com.example.smartg.utils.ToastUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


public class SmartGMainActivity extends AppCompatActivity {

    String key="";
    int try_times=0;
    int overtime_flag=1;
    //加上计时器
    private Timer mTimer; // 计时器，每2秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns
    private ImageView gle_logo;
    private TextView textViewUsername;
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        SpUtils.putLong(SmartGMainActivity.this,"lastActionTime",System.currentTimeMillis());
        return super.dispatchTouchEvent(ev);
    }


    @Override
    protected void onDestroy(){
        stopTimer();
        super.onDestroy();
    }
    @Override
    protected void onPause() {
        stopTimer();
        super.onPause();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smart_gmain);
        // #start 管理员通用模块
        textViewUsername = (TextView) findViewById(R.id.user_name);
        gle_logo = (ImageView) findViewById(R.id.scan_code_origin) ;
        String user_name = SpUtils.getString(this,"user_name","未登录");
        textViewUsername.setText(user_name);
        if(user_name.equals("未登录")){
            gle_logo.setImageResource(R.drawable.gle_logo);
            gle_logo.setVisibility(View.VISIBLE);
        }else{
            gle_logo.setVisibility(View.GONE);
        }
        textViewUsername.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = SpUtils.getString(SmartGMainActivity.this,"user_name","未登录");
                if(name.equals("未登录")){
                    Intent intent = new Intent(SmartGMainActivity.this,LoginNavActivity.class);
                    startActivity(intent);
                }else{
                    LogoutDialogUtil.logout(SmartGMainActivity.this);
                }
            }
        });
        // #end 管理员通用模块

        ImageButton qujian = (ImageButton) findViewById(R.id.qujian);
        qujian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ToastUtil.success(SmartGMainActivity.this,"请输入6位取件码!");
                String token = SpUtils.getString(SmartGMainActivity.this,"token","");
                Log.e("token:",token);
                if(token.equals("")){
                    Intent intent = new Intent(SmartGMainActivity.this,LoginNavActivity.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(SmartGMainActivity.this,QuJianActivity.class);
                    startActivity(intent);
                }
            }
        });
        ImageButton jijian = (ImageButton) findViewById(R.id.jijian);
        jijian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String token = SpUtils.getString(SmartGMainActivity.this,"token","");
                Log.e("token:",token);
                if(token.equals("")){
                    Intent intent = new Intent(SmartGMainActivity.this,LoginNavActivity.class);
//                    Intent intent = new Intent(SmartGMainActivity.this,JiJianActivity.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(SmartGMainActivity.this,JiJianActivity.class);
                    startActivity(intent);
                }
            }
        });
        ImageButton kuandiyuan = (ImageButton) findViewById(R.id.kuandiyuan);
        kuandiyuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String token = SpUtils.getString(SmartGMainActivity.this,"token","");
                Log.e("token:",token);
                if(token.equals("")){
                    Intent intent = new Intent(SmartGMainActivity.this,LoginNavActivity.class);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(SmartGMainActivity.this,ManagerLoginActivity.class);
                    startActivity(intent);
                }
            }
        });
        gle_logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = SpUtils.getString(SmartGMainActivity.this,"user_name","未登录");
                if(name.equals("未登录")){
                    key = UUID.randomUUID().toString().replace("-","");
                    String url = "http://10.2.47.115/gm_user/get_agv_mini_code?page=packageB/pages/package/smart_box/scan_login/scan_login&env_version=release&_id=" + key;
                    try_times = 0;
                    overtime_flag = 0;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide
                                    .with(SmartGMainActivity.this)
                                    .load(url)
                                    .placeholder(R.drawable.loading)
                                    .into(gle_logo);
                        }
                    });
                }else{
                    LogoutDialogUtil.logout(SmartGMainActivity.this);
                }

            }
        });
        get_empty_num();
        startTimer();
    }

    //查询空闲格口
    public void get_empty_num(){
        String url = "http://10.2.47.115/smartg_api/deposit_manage/query_cabinet_size";
        //实例化
        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("cabinet_id", "YS001");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("exception", e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(SmartGMainActivity.this, "查询空箱数量报错！");
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                Log.e("res2", responsedata);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    JSONArray data = jsonObject.optJSONArray("data");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code == 20000) {
                                int big = 0;
                                int mid = 0;
                                int small = 0;
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject item = data.optJSONObject(i);
                                    String item_type = item.optString("size");
                                    if (item_type.equals("big")) {
                                        big = item.optInt("count");
                                    } else if (item_type.equals("mid")) {
                                        mid = item.optInt("count");
                                    } else {
                                        small = item.optInt("count");
                                    }
                                }
                                TextView s_num = (TextView) findViewById(R.id.empty_s_num);
                                s_num.setText(Integer.toString(small));
                                TextView m_num = (TextView) findViewById(R.id.empty_m_num);
                                m_num.setText(Integer.toString(mid));
                                TextView l_num = (TextView) findViewById(R.id.empty_l_num);
                                l_num.setText(Integer.toString(big));
                            } else {
                                ToastUtil.error(SmartGMainActivity.this,msg);
                            }
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void get_token(String key) {
        String url = "http://10.2.47.115/gm_user/get_smartg_token";
        //实例化
        HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("key", key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.error(SmartGMainActivity.this, "服务器出错！");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                Log.e("responsedata", responsedata);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        JSONObject data = jsonObject.optJSONObject("data");
                        String token = data.optString("token");
                        String user_name = data.optString("name");
                        // 记住用户信息到SharedPreferences
                        SpUtils.putString(SmartGMainActivity.this, "token", token);
                        SpUtils.putString(SmartGMainActivity.this, "user_name", user_name);
                        // 跳转到管理员界面？还是跳转到上一界面?
                        overtime_flag = 1;
                        try_times=0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textViewUsername.setText(user_name);
//                                gle_logo.setImageResource(R.drawable.gle_logo);
                                gle_logo.setVisibility(View.GONE);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onRestart(){
        super.onRestart();
        TextView textViewUsername = (TextView) findViewById(R.id.user_name);
        String user_name = SpUtils.getString(this,"user_name","未登录");
        textViewUsername.setText(user_name);
        get_empty_num();
        startTimer();
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            // 1分钟未操作停止计时并退出登录
            TextView tv = (TextView) findViewById(R.id.countdown3);
            TextView tv0 = (TextView) findViewById(R.id.user_name);
            String real_user_name = SpUtils.getString(SmartGMainActivity.this,"user_name","未登录");
            if (real_user_name.equals("未登录")){
                Log.e("nologin","pass");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("");
                        tv0.setText("未登录");
                        if(overtime_flag==1){
                            gle_logo.setImageResource(R.drawable.gle_logo);
                            gle_logo.setVisibility(View.VISIBLE);
                        }
                    }
                });
                SpUtils.putLong(SmartGMainActivity.this,"lastActionTime",System.currentTimeMillis());
                if(overtime_flag==0){
                    try_times += 1;
                    if(try_times >=50){
                        overtime_flag =1 ;
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                gle_logo.setImageResource(R.drawable.gle_logo);
//                            }
//                        });
                    }else{
                        get_token(key);
                    }
                }
            }else{
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        gle_logo.setVisibility(View.GONE);
                    }
                });
                long lastActionTime = SpUtils.getLong(SmartGMainActivity.this,"lastActionTime",0);
                int leftSeconds = (int) (System.currentTimeMillis() - lastActionTime - 5000) / 1000;
                if(leftSeconds > 0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText((60 -leftSeconds ) + "秒后退出！！");
                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText("");
                        }
                    });
                }
                Log.e("=1=", (System.currentTimeMillis() - lastActionTime - 5000) / 1000 + "");
                if (System.currentTimeMillis() - lastActionTime - 5000 > 1000 * 60 * 1) {
                    SpUtils.clear(SmartGMainActivity.this);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText("");
                        }
                    });
                }
            }


        }
    }

    public void stopTimer() {
        Log.e("=1=", "主页定时任务关闭");
        mTimer.cancel();
    }

    private void startTimer() {
        Log.e("=00000=", "start_timer");
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        SpUtils.putLong(SmartGMainActivity.this,"lastActionTime",System.currentTimeMillis());
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 1000);
        //Log.e(TAG, "登录成功开始计时");

    }
}